package com.wiseasy.smartpos.cashierdemo.pinpad;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.wiseasy.smartpos.cashierdemo.R;
import com.wiseasy.smartpos.cashierdemo.util.DeviceUtils;
import com.wisepos.smartpos.WisePosException;
import com.wisepos.smartpos.WisePosSdk;
import com.wisepos.smartpos.pinpad.KeyRegion;
import com.wisepos.smartpos.pinpad.KeyRegionType;
import com.wisepos.smartpos.pinpad.PinInputListener;
import com.wisepos.smartpos.pinpad.PinOption;
import com.wisepos.smartpos.pinpad.Pinpad;
import com.wisepos.smartpos.pinpad.PinpadRegion;
import com.wisepos.smartpos.transaction.TransProcess;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;


public class PinpadDialog implements Handler.Callback,IPinpadDialog {
    private Activity activity;
    private Dialog mDialog;
    private TextView[] tvDigits = new TextView[10];
    private Button btnCancel;
    private View tvDelete;
    private View tvOk;
    private View keyboard;

    private TextView mTvTitle;
    private TextView mTvAmount;
    private TextView mTvTips;
    private TextView mTvPassword;

    private PinOption pinOption = null;
    private PinpadRegion pinpadRegion = null;
    private Pinpad pinpad = null;

    private PinpadResultListener listener;
    private Handler handler = null;
    private TransProcess transProcess;
    private int pinType;

    public PinpadDialog(Activity activity, Intent intent, PinpadResultListener listener) {
        this.activity = activity;
        this.listener = listener;
        transProcess = WisePosSdk.getInstance().getTransProcess();
        pinpad = WisePosSdk.getInstance().getPinpad();
        handler = new Handler(activity.getMainLooper(), this);
        mDialog = new Dialog(activity, R.style.BaseDialog);
        View view = LayoutInflater.from(activity).inflate(R.layout.activity_pinpad, null);

        initView(view);
        handleIntent(intent);
        mDialog.setContentView(view);
        mDialog.setCancelable(false);
        mDialog.onAttachedToWindow();
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnShowListener(dialog -> {
            if (mDialog.isShowing()) {
                doStartInputPin();
            }
        });
    }

    public void show() {
        initStyle();
        mDialog.show();
    }

    public void dismiss() {
        if (mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    private void initView(View view) {


        try {

            View llKeyboardSoft =  view.findViewById(R.id.ll_keyboard_soft);
            View ivKeyboardHard =  view.findViewById(R.id.iv_keyboard_hard);
            btnCancel = (Button) view.findViewById(R.id.id_btn_cancel);

            if(android.os.Build.MODEL.equals("P053")){
                llKeyboardSoft.setVisibility(View.GONE);
                btnCancel.setVisibility(View.INVISIBLE);
                ivKeyboardHard.setVisibility(View.VISIBLE);

            }else {
                tvDigits[0] = (TextView) view.findViewById(R.id.id_tv_0);
                tvDigits[1] = (TextView) view.findViewById(R.id.id_tv_1);
                tvDigits[2] = (TextView) view.findViewById(R.id.id_tv_2);
                tvDigits[3] = (TextView) view.findViewById(R.id.id_tv_3);
                tvDigits[4] = (TextView) view.findViewById(R.id.id_tv_4);
                tvDigits[5] = (TextView) view.findViewById(R.id.id_tv_5);
                tvDigits[6] = (TextView) view.findViewById(R.id.id_tv_6);
                tvDigits[7] = (TextView) view.findViewById(R.id.id_tv_7);
                tvDigits[8] = (TextView) view.findViewById(R.id.id_tv_8);
                tvDigits[9] = (TextView) view.findViewById(R.id.id_tv_9);
                tvDelete = (View) view.findViewById(R.id.id_ll_delete);
                tvOk = (View) view.findViewById(R.id.id_tv_ok);
            }

            keyboard = (View) view.findViewById(R.id.layout_root);
        } catch (Exception e) {
            notifyFinish(-1, 0);
            return;
        }



        mTvTitle = (TextView) view.findViewById(R.id.id_tv_title);
        mTvAmount = (TextView) view.findViewById(R.id.id_tv_amount);
        mTvTips = (TextView) view.findViewById(R.id.id_tv_tips);
        mTvPassword = (TextView) view.findViewById(R.id.id_tv_pass);
    }

    private PinpadRegion getPinpadRegion(Object[] buttonNum, Object buttonKeyboard, Object buttonOK, Object buttonDel, Object buttonCancel) {
        int i;

        PinpadRegion pinpadRegion1 = new PinpadRegion();
        KeyRegion keyboardRegion;
        List<KeyRegion> funKeyList = new ArrayList();
        List<KeyRegion> randKeyRegionList = new ArrayList();

        keyboardRegion = new KeyRegion(this.getX((View) buttonKeyboard, "left"), this.getY((View) buttonKeyboard, "top"), this.getX((View) buttonKeyboard, "right"), this.getY((View) buttonKeyboard, "bottom"), KeyRegionType.KEY_REGION_TYPE_KEYBOARD);
        pinpadRegion1.setKeyboardRegion(keyboardRegion);
        funKeyList.add(new KeyRegion(this.getX((View) buttonDel, "left"), this.getY((View) buttonDel, "top"), this.getX((View) buttonDel, "right"), this.getY((View) buttonDel, "bottom"), KeyRegionType.KEY_REGION_TYPE_DELETE));
        funKeyList.add(new KeyRegion(this.getX((View) buttonCancel, "left"), this.getY((View) buttonCancel, "top"), this.getX((View) buttonCancel, "right"), this.getY((View) buttonCancel, "bottom"), KeyRegionType.KEY_REGION_TYPE_CANCEL));
        funKeyList.add(new KeyRegion(this.getX((View) buttonOK, "left"), this.getY((View) buttonOK, "top"), this.getX((View) buttonOK, "right"), this.getY((View) buttonOK, "bottom"), KeyRegionType.KEY_REGION_TYPE_ENTER));
        pinpadRegion1.setFuncKeyList(funKeyList);

        for (i = 0; i < 10; ++i) {
            randKeyRegionList.add(new KeyRegion(this.getX((View) buttonNum[i], "left"), this.getY((View) buttonNum[i], "top"), this.getX((View) buttonNum[i], "right"), this.getY((View) buttonNum[i], "bottom"), KeyRegionType.KEY_REGION_TYPE_NUMBER));
        }

        pinpadRegion1.setNumKeyList(randKeyRegionList);
        return pinpadRegion1;
    }

    private int getX(View view, String orientation) {
        int[] loc = {0, 0};
        int w;
        view.getLocationInWindow(loc);
        view.getLocationOnScreen(loc);

        w = view.getWidth();
        if (orientation.equals("left")) {
            return loc[0];
        } else if (orientation.equals("right")) {
            return (loc[0] + w);
        }
        return 0;

    }

    private int getY(View view, String orientation) {
        int[] loc = {0, 0};
        int h;
        view.getLocationInWindow(loc);
        view.getLocationOnScreen(loc);
        h = view.getHeight();
        if (orientation.equals("top")) {
            return loc[1];
        } else if (orientation.equals("bottom")) {
            return (loc[1] + h);
        }
        return 0;
    }

    private void handleIntent(Intent intent) {
        if (intent != null) {
            pinType = intent.getIntExtra("PinType", 1);
            int transType = intent.getIntExtra("Title", -1);
            int position = -1;
            if (transType == 0) {
                position = 0;
            } else if (transType == 1) {
                position = 1;
            } else if (transType == 9) {
                position = 2;
            } else if (transType == 20) {
                position = 3;
            } else {
                position = -1;
            }
            if (position < 0 || position > 3) {
                notifyFinish(-1, 0);
                return;
            }
            String[] titles = activity.getResources().getStringArray(R.array.trans_type);
            mTvTitle.setText((String) Array.get(titles, position));
            long amt = intent.getLongExtra("Amount", -1);
            if (amt < 0 || amt > Long.MAX_VALUE) {
                notifyFinish(-1, 0);
                return;
            }
            if (DeviceUtils.isE1Lite()){
                if (DeviceUtils.isE1Lite()){
                    mTvAmount.setGravity(Gravity.LEFT);
                    mTvAmount.setText(intent.getStringExtra("amountWithSymbol"));
                }
            }else {
                mTvAmount.setText(String.valueOf(amt));
            }

            String tips = intent.getStringExtra("Tips");
            mTvTips.setText(tips);
            String hint = intent.getStringExtra("PwdHint");
            mTvPassword.setText(hint);
        }
    }

    private void initStyle() {
        Window dialogWindow = mDialog.getWindow();
        WindowManager m = activity.getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = dialogWindow.getAttributes();

        Configuration cf = activity.getResources().getConfiguration();
        int ori = cf.orientation;
        if (ori == cf.ORIENTATION_LANDSCAPE) {
            p.width = (int) (d.getWidth() * 0.6);
            p.height = (int) (d.getHeight() * 0.8);
            p.gravity = Gravity.CENTER;
            p.alpha = 0.8f;
        } else if (ori == cf.ORIENTATION_PORTRAIT) {
            p.height = (int) (d.getHeight() * 0.8);
            p.gravity = Gravity.CENTER;
            p.alpha = 0.8f;
        }
        dialogWindow.setAttributes(p);
    }

    private void doStartInputPin() {
        if (pinpad == null) {
            notifyFinish(-1, 0);
            return;
        }
        pinOption = new PinOption();
        pinOption.setBeepWhenPressKey(true);
        pinOption.setOptZeroPinLen(1);
        if(pinType == 1){
            pinOption.setRandomKeyPad(true);
        }else {
            pinOption.setRandomKeyPad(false);
        }

        new Thread(() -> {
            try {
                if(android.os.Build.MODEL.equals("P053")){
                    pinpad.startPinInputFromKbd(1, pinOption, inputListener);
                } else {
                     pinpadRegion = getPinpadRegion(tvDigits, keyboard, tvOk, tvDelete, btnCancel);
                     pinpad.startPinInput(pinType, pinOption, pinpadRegion, inputListener);
                }
            } catch (WisePosException e) {
                e.printStackTrace();
            }
        }).start();

    }

    private void updatePassword(int len) {
        char[] chars = new char[len];
        for (int i = 0; i < len; i++) {
            chars[i] = '*';
        }
        mTvPassword.setText(String.valueOf(chars));
    }

    private void reInputPin(int sw1sw2) {
        mTvPassword.setText("");
        if (sw1sw2 == 0x63C1) {
            mTvPassword.setText("Last retry");
        } else if ((sw1sw2 & 0x63C0) == 0x63C0) {
            mTvPassword.setText("Enter PIN again");
        }
        new Thread(() -> {
            try {
                if(android.os.Build.MODEL.equals("P053")){
                    pinpad.startPinInputFromKbd(1, pinOption, inputListener);
                } else {
                    pinpad.startPinInput(pinType, pinOption, pinpadRegion, inputListener);
                }
            } catch (WisePosException e) {
                e.printStackTrace();
            }
        }).start();

    }

    private PinInputListener inputListener = new PinInputListener() {
        @Override
        public void onStartPinInput(String s) {
            Message msg = Message.obtain();
            Bundle bd = new Bundle();
            bd.putString("data", s);
            msg.setData(bd);
            msg.what = 1;
            handler.sendMessage(msg);
        }

        @Override
        public void onKeyEvent(int pinLength, int type) {
            Message msg = Message.obtain();
            msg.what = 0;
            msg.arg1 = pinLength;
            handler.sendMessage(msg);
        }

        @Override
        public void onPinResult(int errCode, int sw1sw2) {
            if (sw1sw2 != 0x63C0 && (sw1sw2 & 0x63C0) == 0x63C0) {
                Message msg = Message.obtain();
                msg.what = 2;
                msg.arg1 = errCode;
                msg.arg2 = sw1sw2;
                handler.sendMessage(msg);
            } else {
                notifyFinish(errCode, sw1sw2);
            }
        }
    };

    private void notifyFinish(int code, int sw1sw2) {
        Message msg = Message.obtain();
        msg.what = 3;
        msg.arg1 = code;
        msg.arg2 = sw1sw2;
        handler.sendMessage(msg);
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case 0:
                updatePassword(msg.arg1);
                break;
            case 1:
                Bundle bd = null;
                bd = msg.getData();
                String data = bd.getString("data");
                if(!TextUtils.isEmpty(data)) {
                    tvDigits[0].setText(data.substring(0, 1));
                    tvDigits[1].setText(data.substring(1, 2));
                    tvDigits[2].setText(data.substring(2, 3));
                    tvDigits[3].setText(data.substring(3, 4));
                    tvDigits[4].setText(data.substring(4, 5));
                    tvDigits[5].setText(data.substring(5, 6));
                    tvDigits[6].setText(data.substring(6, 7));
                    tvDigits[7].setText(data.substring(7, 8));
                    tvDigits[8].setText(data.substring(8, 9));
                    tvDigits[9].setText(data.substring(9, 10));
                }
                break;
            case 2:
                reInputPin(msg.arg2);
                break;
            case 3:
                if (listener != null) {
                    listener.onPinpadResultListener(msg.arg1, msg.arg2);
                }
                mDialog.dismiss();
                break;
            default:
                break;
        }
        return false;
    }

    public interface PinpadResultListener {
        void onPinpadResultListener(int code, int sw1sw2);
    }
}
